$(document).ready(function(){

    /*** Upload new picture ***/
$('#file_upload').uploadify({
    'uploader'        : WebRoot + 'js/uploadify/uploadify.swf',
    'cancelImg'       : WebRoot + 'js/uploadify/cancel.png',
    'buttonText'      : textUploadify,
    'buttonImg'       : WebRoot + 'js/uploadify/add.png',
    'removeCompleted' : false,    
    'sizeLimit'       : 8388608,        
    //'sizeLimit'       : 2388608,        
    'scriptData'      : {'idAlbum': $('#idAlbum').val()},
    'script'          : WebRoot + 'controllers/upload.php',
    'displayData'     : 'percentage', 
    //'displayData'     : 'speed', 
    'method'          : 'post',
    'fileExt'         : '*.jpg;*.gif;*.png',
    'fileDesc'        : 'Image Files (*.jpg, *.gif, *.png)',
    'multi'           : true,      
    'auto'            : true,
    'queueID'         : 'fileUploadQueue',
    'width'           : 16,
    'height'          : 16,
    'wmode'           : 'transparent',
    //'hideButton'      : true,
  onSelectOnce        : function() { 
                          $('#fileUploadQueue').dialog({
                            buttons       : [{text: "Ok",
                                               click: function() {$(this).dialog("close");}
                                            }],
                            beforeClose   : function(){
                                              location.reload();
                                            },
                            closeOnEscape : false,
                            draggable     : true,
                            minHeight     : 400,
                            width         : 910,
                            modal         : true,
                            resizable     : false,
                            title         : textUploadify
                          });
                        },  
  onComplete          : function(event, ID, fileObj, response, data) {
    
                          if (response.toString() != 'OK') {
                            errMsg = ' - ' + response.toString().substring(4);
                            $('#file_upload' + ID).addClass('uploadifyError');
                            $('#file_upload' + ID).removeClass('completed');
                            setTimeout('$(\'#file_upload' + ID + ' .percentage\').text(errMsg)', 400);
                          }
                        },  
  onAllComplete       : function(event,data) {  
                          $.ajax({
                                  type : "POST",
                                  data : ({uploaded: data.filesUploaded, album: $('#idAlbum').val()}),
                                  url  : WebRoot + 'controllers/notifyUpload.php' 
                          });
                          //$('.item_photo').load(location.href+" .item_photo>*",""); 
                          //location.reload();        
                        }    
});

    /*** Show large picture in fancybox ***/
function formatTitle(title, currentArray, currentIndex, currentOpts) {

  idPhoto = title;          
  var html; 
    
  $.ajax({
          type: "GET",
          url: WebRoot + "controllers/title.php?idPhoto=" + idPhoto,      
          async: false,
          complete: function(msg){        
            html = msg.responseText;
          }
  });
  
     html = html.replace("$1$", currentIndex + 1);
     html = html.replace('$2$', currentArray.length);
  return html;
}

    /*** Show fancybox if photo is requested  ***/
if (window.location.hash) {  
  $('#photo_' + window.location.hash.substr(1)).fancybox({'titlePosition'  : 'outside',                                   
                                                          'titleFormat'    : formatTitle,                    
                                                          'onComplete'	   : function() {
                                                                               window.location.hash = this.title;
                                                                             },
                                                          'onClosed'       : function() {
                                                                               window.location.hash = null;  
                                                                             }
                                                         }).trigger('click');
}

    /*** Show fancybox if clicked  ***/
$('.fancy_photo').fancybox({'titlePosition'  : 'outside',
                            //'scrolling'      : 'yes',
                            //'centerOnScroll'      : true,
                            
                            'titleFormat'    : formatTitle,                    
                            'onComplete'	   : function() {
                                                 window.location.hash = this.title;
                                                /* $("#fancybox-wrap").hover(function() {
			                                                                       $(".title_hid").show();
		                                                                       }, function() {
			                                                                       $(".title_hid").hide();
		                                                                       });*/
                                               },
                            'onClosed'       : function() {
                                                 window.location.hash = null;  
                                               }                    
                           });

    /*** checking of existing data in a database ***/
$('#formDisplayNameLoading').hide();
$('#registerEmailLoading').hide();

$('#registerEmail').blur(function(){
  $('#registerEmailLoading').show();
  $.post(WebRoot + "controllers/verifyeMail.php", {
          'eMail': $('#registerEmail').val()          
  }, function(response){
    $('#registerEmailResult').fadeOut();
    setTimeout("finishAjax('registerEmailResult', '"+escape(response)+"')", 400);
  });
    $('#formDisplayName').val($('#registerEmail').val().substr(0, $('#registerEmail').val().search('@')));
    	return false;
	});

$('#formDisplayName').blur(function(){
  $('#formDisplayNameLoading').show();
  $.post(WebRoot + "controllers/verifyUserName.php", {
          'userName': $('#formDisplayName').val()          
  }, function(response){
    $('#formDisplayNameResult').fadeOut();
    setTimeout("finishAjax('formDisplayNameResult', '"+escape(response)+"')", 400);
  });    
    	return false;
	});


/*** Show a title ***/
$('.tooltipTitle').tooltip({ 	position: "center right",
                              offset: [-30, 5],
                              effect: "fade",
                              opacity: 0.7 
                          });

    /*** autocomplete and showing proper form for protection ***/
$('#autocompleteUserLoading').hide();

if ($('#formProtection').val() != 'private') {
  $('#autocompleteUser').hide();
  $('#autocompleteUserLabel').hide();
  $('#placeForCheckBox').hide();
}

if ($('#formProtection').val() != 'password') {
  $('#formPassword').hide();
  $('#formPasswordLabel').hide();
}  


$('#formProtection').change(function(){
  
  $('#formPassword').hide();
  $('#formPasswordLabel').hide();
  $('#autocompleteUser').hide();
  $('#autocompleteUserLabel').hide();
  $('#placeForCheckBox').hide();  
  
  if ($(this).val() == 'password') {
    $('#formPassword').show();
    $('#formPasswordLabel').show();
  }

  if ($(this).val() == 'private') {
    $('#autocompleteUser').show();
    $('#autocompleteUserLabel').show();    
    $('#placeForCheckBox').show();  
  }
    
});

/*
$('#submitComment').attr('disabled', 'disabled')

$('#formComment').change(function(){
  if ($('#submitComment').val() == '') 
    $('#submitComment').attr('disabled', 'disabled');
  else
    $('#submitComment').removeAttr('disabled');
});  */

 $('#autocompleteUser').autocomplete({
    source    : WebRoot + 'controllers/my_autocomplete_backend.php',
    minLength : 3,
    search    : function() {
                             $('#autocompleteUserLoading').show();
                           },
    open      : function() {
                             $('#autocompleteUserLoading').hide();
                           },                           
    select    : function(event, ui) { 
      console.log($('#ac_' + ui.item.value).length);
                                    if(!$('#ac_' + ui.item.value).length)
                                      $('#placeForCheckBox .clear').before('<div class="checkBoxes-new"><input type="checkbox" checked="checked" id="ac_' + ui.item.value + '" name="allowedUsers[]" value="' + ui.item.value + '" />\n\
                                                                     <label for="ac_' + ui.item.value + '">' + ui.item.value + '</label></div>');                         
                                    },
    close : function () { $('#autocompleteUser').val(null);  $('#autocompleteUserLoading').hide();}
});

    /*** preview of theme ***/
var originalStyle;
$('.changestyle').hover(function(){
                          originalStyle = $("link").attr("href");
                          $("link").attr("href", WebRoot + 'themes/' + $(this).attr('rel') + '/style.css');
                        }, function() {
                          //$("link").attr("href", originalStyle);
                        });

    /*** Password strength meter ***/
$('#registerPassword').keyup(function(){
  $('#registerPasswordResult').html( passwordStrength($('#registerPassword').val(), $('#registerEmail').val()) );
});
    

});

function finishAjax(id, response) {
  $('#registerEmailLoading').hide();
  $('#formDisplayNameLoading').hide();
  $('#'+id).html(unescape(response));
  $('#'+id).fadeIn();
} 
